package com.spica.spicaschool.ui.sport

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.drakeet.multitype.ItemViewDelegate
import com.spica.spicaschool.R
import com.spica.spicaschool.bean.SportMotionRecord
import com.spica.spicaschool.databinding.ItemSportMotionRecordBinding
import java.math.RoundingMode
import java.text.DecimalFormat

/**
 * 运动轨迹记录适配器
 */
class SportRecordDelegate(context: Context) :
  ItemViewDelegate<SportMotionRecord, SportRecordDelegate.ViewHolder>() {

  //用于随机取色的列表
  private val colors = listOf(
    context.getColor(R.color.ThemePurple),
    context.getColor(R.color.ThemeYellow),
    context.getColor(R.color.ThemeGreen),
    context.getColor(R.color.ThemeBlack),
    context.getColor(R.color.ThemeBlue),
    context.getColor(R.color.ThemePurple),
    context.getColor(R.color.ThemeYellow),
    context.getColor(R.color.ThemeGreen),
    context.getColor(R.color.ThemeBlack),
    context.getColor(R.color.ThemeBlue)
  )


  class ViewHolder(val viewBinding: ItemSportMotionRecordBinding) :
    RecyclerView.ViewHolder(viewBinding.root)

  @SuppressLint("SetTextI18n")
  override fun onBindViewHolder(holder: ViewHolder, item: SportMotionRecord) {
    holder.viewBinding.tvName.text = "NO.${getPosition(holder) + 1}"
    holder.viewBinding.tvTime.text = item.dateTag
    holder.viewBinding.tvTimeNum.text = "${(item.duration?.toDouble()?.div(60))?.formatString()}"
    holder.viewBinding.tvDistanceNum.text = "${item.distance?.formatString()}"
    val index = getPosition(holder) % colors.size
    holder.viewBinding.root.setCardBackgroundColor(colors[index])
  }


  override fun getItemId(item: SportMotionRecord): Long {
    return item.id ?: 0L
  }

  override fun onCreateViewHolder(context: Context, parent: ViewGroup): ViewHolder {
    val viewBinding =
      ItemSportMotionRecordBinding.inflate(LayoutInflater.from(context), parent, false)
    return ViewHolder(viewBinding)
  }


  private fun Double.formatString(): String {
    val format = DecimalFormat("0.##")
    //未保留小数的舍弃规则，RoundingMode.FLOOR表示直接舍弃。
    format.roundingMode = RoundingMode.FLOOR
    return format.format(this)
  }


}